package com.hxb.example.chatModel.openapi.service;

import com.hxb.example.service.ChatModelService;
import jakarta.annotation.Resource;
import org.springframework.ai.autoconfigure.openai.OpenAiChatProperties;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.model.Generation;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@ConditionalOnProperty(prefix = OpenAiChatProperties.CONFIG_PREFIX, name = "enabled", havingValue = "true")
public class OpenApiService implements ChatModelService {
    @Resource
    private OpenAiChatModel chatModel;


    @Override
    public String call(String message) {
        String name = "小明";
        String userText = """
                给我推荐上海的至少三个旅游景点
                """;

        Message userMessage = new UserMessage(userText);

        String systemText = """
                你是一个有用的人工智能助手，可以帮助人们查找信息，
                你的名字是{name}，
                你应该用你的名字和{voice}的风格回复用户的请求。
                """;

        SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemText);
        Message systemMessage = systemPromptTemplate.createMessage(Map.of("name", name, "voice", message));

        Prompt prompt = new Prompt(List.of(userMessage, systemMessage));
        List<Generation> response = chatModel.call(prompt).getResults();
        StringBuilder result = new StringBuilder();
        for (Generation generation : response) {
            String content = generation.getOutput().getContent();
            result.append(content);
        }
        return result.toString();
    }

    @Override
    public Flux<ChatResponse> streamCall(String message) {
        Prompt prompt = new Prompt(message);
        return chatModel.stream(prompt);
    }

    @Override
    public String functionCall(String message) {
        String systemPrompt = "{prompt}";
        SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemPrompt);
        Message systemMessage = systemPromptTemplate.createMessage(Map.of("prompt", "你是一个有用的人工智能助手"));

        Message userMessage = new UserMessage(message);
        Prompt prompt = new Prompt(List.of(userMessage, systemMessage),
                OpenAiChatOptions.builder().withFunctions(Set.of("addressFunction", "coordinateFunction")).build());
        return chatModel.call(prompt).getResults().stream().map(generation -> generation.getOutput().getContent())
                .collect(Collectors.joining(","));
    }

    @Override
    public Flux<ChatResponse> functionStreamCall(String message) {
        SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate("{prompt}");
        Message systemMessage = systemPromptTemplate.createMessage(Map.of("prompt", "你是一个有用的人工智能助手"));

        Message userMessage = new UserMessage(message);
        Prompt prompt = new Prompt(List.of(userMessage, systemMessage),
                OpenAiChatOptions.builder().withFunctions(Set.of("currentWeather", "currentPopulation")).build());

        return chatModel.stream(prompt);
    }

    // public Response image(@RequestParam(value = "description") String description) {
    //     ImageResponse response = imageClient.call(
    //             new ImagePrompt(description,
    //                     OpenAiImageOptions.builder().withQuality("hd").withN(1).withHeight(1024).withWidth(1024).build()));
    //     return Response.ok(response.getResults().get(0).getOutput().getUrl());
    // }

    // public Response Response(@RequestParam(value = "actor") String actor) {
    //     BeanOutputParser<ActorsFilms> outputParser = new BeanOutputParser<>(ActorsFilms.class);
    //
    //     String userMessage = """
    //             为演员{actor}生成电影作品年表。
    //             {format}
    //             """;
    //     logger.info("output format:{}", outputParser.getFormat());
    //     PromptTemplate promptTemplate = new PromptTemplate(userMessage, Map.of("actor", actor, "format", outputParser.getFormat()));
    //     Prompt prompt = promptTemplate.create();
    //     Generation generation = chatClient.call(prompt).getResult();
    //
    //     ActorsFilms actorsFilms = outputParser.parse(generation.getOutput().getContent());
    //     return Response.ok(JacksonUtil.toJson(actorsFilms));
    // }
}
